include(SanitizeInput)

# Fall back to the previous cmake configuration, "USE_BUNDLED_ZLIB"
if(NOT USE_COMPRESSION AND USE_BUNDLED_ZLIB)
	SanitizeInput(USE_BUNDLED_ZLIB)

	if(USE_BUNDLED_ZLIB STREQUAL ON)
		set(USE_COMPRESSION "builtin")
	elseif(USE_BUNDLED_ZLIB STREQUAL OFF)
		set(USE_COMPRESSION "zlib")
	else()
		message(FATAL_ERROR "unknown setting to USE_BUNDLED_ZLIB: ${USE_BUNDLED_ZLIB}")
	endif()
endif()

SanitizeInput(USE_COMPRESSION)

if(NOT USE_COMPRESSION)
	find_package(ZLIB)

	if(ZLIB_FOUND)
		set(GIT_COMPRESSION_ZLIB 1)
	else()
		message(STATUS "zlib was not found; using bundled 3rd-party sources." )
		set(GIT_COMPRESSION_BUILTIN 1)
	endif()
elseif(USE_COMPRESSION STREQUAL "zlib")
	find_package(ZLIB)

	if(NOT ZLIB_FOUND)
		message(FATAL_ERROR "system zlib was requested but not found")
	endif()

	set(GIT_COMPRESSION_ZLIB 1)
elseif(USE_COMPRESSION STREQUAL "builtin")
	set(GIT_COMPRESSION_BUILTIN 1)
endif()

if(GIT_COMPRESSION_ZLIB)
	list(APPEND LIBGIT2_SYSTEM_INCLUDES ${ZLIB_INCLUDE_DIRS})
	list(APPEND LIBGIT2_SYSTEM_LIBS ${ZLIB_LIBRARIES})
	if(APPLE OR CMAKE_SYSTEM_NAME MATCHES "FreeBSD")
		list(APPEND LIBGIT2_PC_LIBS "-lz")
	else()
		list(APPEND LIBGIT2_PC_REQUIRES "zlib")
	endif()
	add_feature_info("Compression" ON "using system zlib")
elseif(GIT_COMPRESSION_BUILTIN)
	add_subdirectory("${PROJECT_SOURCE_DIR}/deps/zlib" "${PROJECT_BINARY_DIR}/deps/zlib")
	list(APPEND LIBGIT2_DEPENDENCY_INCLUDES "${PROJECT_SOURCE_DIR}/deps/zlib")
	list(APPEND LIBGIT2_DEPENDENCY_OBJECTS $<TARGET_OBJECTS:zlib>)
	add_feature_info("Compression" ON "using bundled zlib")
else()
	message(FATAL_ERROR "unknown compression backend")
endif()
